#!/bin/bash

# load install functions
. vserver.functions

# Check if sudo is installed on this machine.
function detect_sudo() {

	if ! isSudoAvailable ; then
		echo 
		echo "You have to install the sudo package to be able to install vserver."
		echo "Please install it or contact the system administrator."
		echo
		exit 1
	fi
}

function detect_management_tool() {

	if isAptAvailable
	then
		echo " apt tool detected. Preparing to install the packages: linux-image-vserver-686 util-vserver ssh "
		install_packages
		if isVServerAvailable 
		then
			echo 
			echo "================================="
			echo " Well done boy. VServer was succesfully installed"
			echo "================================="
			echo
		else 
			echo 
			echo "================================="
			echo " An error ocurred in the apt-get install process, vserver could not be installed. Calling Garbage collector ..."
			echo "================================="
			echo 
			remove_packages
			exit 1
		fi
	else
		echo 
		echo "================================="
		echo " A management tool (apt, yum etc) was not detected, the installation was aborted. "
		echo "================================="
		echo
		exit 1
	fi
}

function detect_kernel_install() {
 
	if isVServer_KernelAvailable 
	then
		echo
 		echo "================================="
		echo " Well done boy. VServer kernel was sucessfully installed, pleasy reboot the machine."
		echo "================================="
		echo 
	else 
		echo
		echo "================================="
		echo " VServer kernel could not be installed please contact your revendor."
		echo "================================="
		echo
		exit 1
	fi 
}

# TODO: Assign the packages names into a variable 
function install_packages() {
	apt-get -y install linux-image-vserver-686 util-vserver ssh
}

function remove_packages() {
	apt-get -y remove linux-image-vserver-686 util-vserver
}

# main() - Checking for dependencies.
echo
echo "================================="
echo "   Ready to begin installation   "
echo "================================="
echo
echo "==========================="
echo "   Checking dependencies   "
echo "==========================="
echo

echo -n "Checking for Sudo... "
detect_sudo
echo "OK"
echo

# main() - Configuring VServer.
echo
echo "================================================="
echo "   Configuring VServer"
echo "   Detecting distro package management tools ... "
echo "================================================="
echo

detect_management_tool
detect_kernel_install

echo
echo "====================================="
echo "   You're done. VServer is installed."
echo "====================================="
echo
